package cn.tjad.tjad2.module.form.views;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatSpinner;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import cn.tjad.tjad2.BuildConfig;
import cn.tjad.tjad2.data.bean.FormDetail;

public class SpinnerView extends FormBaseLayout {
    public SpinnerView(Context context) {
        super(context);
    }

    public SpinnerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setFormStepDetail(FormDetail.FormStepDetail formStepDetail) {
        super.setFormStepDetail(formStepDetail);
        addBodyView();
    }

    private void addBodyView() {
        AppCompatSpinner spinner = new AppCompatSpinner(getContext());
        FormDetail.Detail detail = formStepDetail.detail;
        if (detail.selection != null) {
            String[] elements = detail.selection.split(",");
            ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, elements);
            spinner.setAdapter(spinnerAdapter);
            int index = 0;
            for (int i = 0; i < elements.length; i++) {
                if (formStepDetail.value != null && formStepDetail.value.equals(elements[i])) {
                    index = i;
                    break;
                }
            }
            spinner.setSelection(index);
        }
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinner.getAdapter();
                String value = adapter.getItem(position);
                formStepDetail.value = value;
                if (onEditListener != null) {
                    onEditListener.onEdit(formStepDetail.detail.id, value);
                }
                if (BuildConfig.DEBUG) {
                    Log.d("TJAD", "Spinner选项：" + value);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        this.addView(spinner, lp);
    }
}
